#!/bin/bash

#
RSA_HOME=`cd "$(dirname $(readlink -f "$0"))"; pwd`
echo RSA_HOME RESULT: [$RSA_HOME]

#
app_name=resa
app_version="0.0.1-SNAPSHOT"
jar_name="${app_name}-${app_version}.jar"
jarPathName="${RSA_HOME}/${jar_name}"

#
pid_file=resa.pid

#
JVM_OP=" ${JVM_OP} -Xmx8192M"
JVM_OP=" ${JVM_OP} -XX:MetaspaceSize=512M"
JVM_OP=" ${JVM_OP} -XX:MaxMetaspaceSize=512M"
JVM_OP=" ${JVM_OP} -XX:+UseParNewGC"
JVM_OP=" ${JVM_OP} -XX:+UseConcMarkSweepGC"
JVM_OP=" ${JVM_OP} -XX:+PrintGCDetails"
JVM_OP=" ${JVM_OP} -Xloggc:${RSA_HOME}/log/gc.log"
JVM_OP=" ${JVM_OP} -XX:+CMSParallelInitialMarkEnabled"
JVM_OP=" ${JVM_OP} -XX:+PrintGCTimeStamps"
JVM_OP=" ${JVM_OP} -XX:+DisableExplicitGC"
JVM_OP=" ${JVM_OP} -XX:+HeapDumpOnOutOfMemoryError"
JVM_OP=" ${JVM_OP} -XX:HeapDumpPath=${RSA_HOME}/log"

#
RUN_OPTIONS=""

#
RUN_OPTIONS=" -Duser.dir=${RSA_HOME}"
RUN_OPTIONS=" ${RUN_OPTIONS} -DRSA_HOME=${RSA_HOME}"
#
RUN_OPTIONS=" ${RUN_OPTIONS} ${JVM_OP}"
#
RUN_OPTIONS=" ${RUN_OPTIONS} -Dspring.config.location=${RSA_HOME}/conf/application.yml"
#
RUN_OPTIONS=" ${RUN_OPTIONS} -Dlogging.config=${RSA_HOME}/conf/logback-spring.xml"
#
RUN_OPTIONS=" ${RUN_OPTIONS} -Dspring.profiles.active=pro"

#
DEBUG_OPTIONS=" ${RUN_OPTIONS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:15055"

#
usage(){
	echo "[start|stop|restart|status]，example：./resa.sh start"
	exit 1
}

#
is_exist(){
	pid=`ps -ef|grep ${jar_name}|grep -v grep|awk '{print $2}'`
	#
	if [ -z "${pid}" ]; then
		return 1
	else
		return 0
	fi
}

#
start(){
	is_exist
	if [ $? -eq "0" ]; then
		echo "${app_name} is already running,pid is ${pid}"
	else
		rm -f ../${pid_file}
		#
		#nohup java ${RUN_OPTIONS} -jar ${jarPathName} >/dev/null 2>&1 &
		java ${RUN_OPTIONS} -jar ${jarPathName}
		#
		echo $! > ../${pid_file}
		echo "${app_name} is start success,pid is $!"
	fi
}

#
stop(){
  #
	is_exist
	if [ $? -eq "0" ]; then
		kill -9 ${pid}
	else
		echo "${app_name} is not running"
	fi
}

#
status(){
	is_exist
	if [ $? -eq "0" ]; then
		echo "${app_name} is running,pid is ${pid}"
	else
		echo "${app_name} is not running"
	fi
}

#
restart(){
	stop
	sleep 5
	start
}

#
case "$1" in
	"start") start;;
	"stop") stop;;
	"status") status;;
	"restart") restart;;
	*) usage;;
esac
